from rest_framework.response import Response
from rest_framework import status
from typing import Any, Optional, Dict
import logging

logger = logging.getLogger(__name__)


class APIResponse:
    """统一的API响应工具类"""
    
    @staticmethod
    def success(data: Any = None, message: str = "操作成功", status_code: int = status.HTTP_200_OK) -> Response:
        """成功响应"""
        response_data = {
            'success': True,
            'message': message
        }
        if data is not None:
            response_data['data'] = data
        
        return Response(response_data, status=status_code)
    
    @staticmethod
    def error(message: str = "操作失败", 
              errors: Optional[Dict] = None, 
              status_code: int = status.HTTP_400_BAD_REQUEST) -> Response:
        """错误响应"""
        response_data = {
            'success': False,
            'message': message
        }
        if errors:
            response_data['errors'] = errors
        
        return Response(response_data, status=status_code)
    
    @staticmethod
    def paginated_success(data: list, 
                         total: int, 
                         page: int = 1, 
                         page_size: int = 10,
                         message: str = "获取成功") -> Response:
        """分页成功响应"""
        return Response({
            'success': True,
            'message': message,
            'data': {
                'results': data,
                'pagination': {
                    'total': total,
                    'page': page,
                    'page_size': page_size,
                    'total_pages': (total + page_size - 1) // page_size
                }
            }
        }, status=status.HTTP_200_OK)
    
    @staticmethod
    def handle_exception(func):
        """异常处理装饰器"""
        def wrapper(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except Exception as e:
                logger.error(f"API异常: {str(e)}", exc_info=True)
                return APIResponse.error(
                    message=f"服务器内部错误: {str(e)}",
                    status_code=status.HTTP_500_INTERNAL_SERVER_ERROR
                )
        return wrapper


def api_exception_handler(func):
    """API异常处理装饰器"""
    import functools

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except ValueError as e:
            return APIResponse.error(message=str(e), status_code=status.HTTP_400_BAD_REQUEST)
        except PermissionError as e:
            return APIResponse.error(message=str(e), status_code=status.HTTP_403_FORBIDDEN)
        except Exception as e:
            logger.error(f"API异常: {str(e)}", exc_info=True)
            return APIResponse.error(
                message="服务器内部错误",
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
    return wrapper
